<!DOCTYPE html>
<html class="x-admin-sm">
{include file='public/header'}
<link rel="stylesheet" type="text/css" href="https://www.jq22.com/jquery/font-awesome.4.6.0.css">
<link rel="stylesheet" href="/admin/xadmin/css/wx_menu.css">
<style>
    .layui-input-block {
        margin-left: 0;
    }

    .layui-form-select {
        width: 66%;
    }
</style>

<body>
    <div class="x-nav">
        <span class="layui-breadcrumb">
            <a href="javascript:void(0)">首页</a>
            <a href="javascript:void(0)">公众号管理</a>
            <a><cite>菜单设置</cite></a>
        </span>
        <a class="layui-btn layui-btn-small" id="reload" title="刷新">
            <i class="layui-icon" style="line-height:30px"><i class="iconfont">&#xe6aa;</i></i>
        </a>
    </div>
    <div class="x-body">
        <div class="fluid">
            <div class="pannel">
                <div class="wx-card">
                    <div class="wx-box">
                        <div class="wx-head"><a href="javascript:;" class="left-icon"><i
                                    class="fa fa-chevron-left"></i></a>微信公众号</div>
                        <div class="wx-body">
                            <p class="content-tips">内容区域</p>
                            <div class="wx-footer">
                                <li class="add-menu"><i class="fa fa-plus"></i></li>
                            </div>
                        </div>
                    </div>
                    <div class="wx-editor">
                        <a href="javascript:;" class="editor-load"><i class="fa fa-spinner"></i></a>
                        <span class="editor-tips">请点击左侧菜单</span>
                        <div class="wx-editor-show">
                            <div class="wx-editor-head"><span class="title">菜单一</span><a class="menu-delete">删除该菜单</a>
                            </div>
                            <div class="wx-editor-body">
                                <div class="cjb-form-group">
                                    <label for="">菜单名称:</label>
                                    <div class="cjb-input-block">
                                        <input type="text" class="cjb-input" name="cjb-name" placeholder="菜单名称">
                                    </div>
                                </div>
                                <div class="cjb-form-group cjb-radio-group">
                                    <label for="">菜单类型:</label>
                                    <div class="cjb-input-block">
                                        <li class="cjb-radio select" type="miniprogram_video">短剧</li>
                                        <li class="cjb-radio" type="miniprogram">小程序</li>
                                        <li class="cjb-radio" type="click">自动回复</li>
                                    </div>
                                </div>
                                <div class="cjb-form-group cjb-val-group">
                                    <label for="">菜单值:</label>
                                    <div id="option">
                                        <div class="cjb-input-block">
                                            <form class="layui-form">
                                                <div id="pVideo" style="width:100%;flex:1"></div>
                                            </form>
                                            <input type="hidden" id="video_id">
                                        </div>
                                        <div class="cjb-input-block" style="display: none;">
                                            <!-- <input type="text" class="cjb-input" name="menu_url" placeholder="小程序地址"> -->
                                            <form class="layui-form">
                                                <div id="pMenu" style="width:100%;flex:1"></div>
                                            </form>
                                            <input type="hidden" id="menu_url">
                                        </div>
                                        <div class="cjb-input-block" style="display: none;">
                                            <textarea name="content" id="content" placeholder="自动回复内容"
                                                class="layui-textarea" autocomplete="off"></textarea>
                                            <span class="layui-badge layui-bg-orange">请勿使用下划线（_）！！！</span>
                                        </div>
                                    </div>
                                </div>
                                <div class="cjb-form-group">
                                    <div class="cjb-input-block">
                                        <!-- <a class="set_menu fluid-btn">确认修改</a> -->
                                        <button type="button" class="layui-btn set_menu">确认修改</button>
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
                <p style="text-align: center;margin-top:10px;">
                    <input type="hidden" name="id" id="menuID" {present name="data.id"}value="{$data.id}"{/present}>
                    <button type="button" class="layui-btn create_menu" data-is_push="0">保存</button>
                    <button type="button" class="layui-btn create_menu" data-is_push="1">保存并发布</button>
                    <!-- <a class="big-btn fluid-btn" style="background-color: #ccc">取消</a> -->
                </p>

            </div>
        </div>
    </div>
    <script>
        var smenu = '<?php echo urlencode(json_encode($data["content"]));?>';
        var menu = JSON.parse(decodeURIComponent(smenu))
        setMenuList(menu.button)
        console.log(menu)

        let selectParams = {
            url: '/cps/video/select',
            selected: [],
            tips: '选择短剧',
            name: 'video_id',
            field_id: 'id',
            field_Name: 'name',
            elem: '#pVideo'
        }
        selectN(selectParams)
        let selectMenu = {
            url: '/cps/officialAccount/appletSelectUrl',
            selected: [],
            tips: '选择地址',
            name: 'menu_url',
            field_id: 'value',
            field_Name: 'name',
            elem: '#pMenu'
        }
        selectN(selectMenu)

        function infoSelectN(option, value) {
            if (option.elem === '#pVideo') {
                $('#video_id').val(value)
            }
            if (option.elem === '#pMenu') {
                $('#menu_url').val(value)
            }
        }

        // https://www.jq22.com/jquery-info21835
        // 当前正在编辑的菜单对象
        var ot = null;
        // 一级菜单点击事件
        $(document).off().on('click', '.menu-item .menu-item-label', function () {
            let t = $(this);
            if (!t.parent().hasClass('ac')) {
                $('.menu-item').removeClass('ac');
                t.parent().addClass('ac');
            }
            $('.title').text($(this).attr('name'))
            $('.child-menu-item').removeClass('active');
            // 呼出编辑器 假装动态加载（‘—’）！！！
            _load(function () {
                $('.wx-editor-show').show(), $('.editor-tips').hide();
            }, 200)

            setFormVal(getMenuVal(t), 1);
            if (t.parent().find('.child-menu-item').length > 0) {
                delMenuVal(t);
            } else {
                $('.cjb-radio-group').show();
                $('.cjb-val-group').show();
                if(t.attr('type') == 'miniprogram'){
                    selectMenu.selected = [t.attr('pagepath')]
                    selectN(selectMenu)
                    selectParams.selected = [t.attr('pagepath')]
                    selectN(selectParams)
                }else{

                }

            }
            ot = t;
        })

        // 二级菜单点击事件
        $(document).on('click', '.child-menu-item .child-menu-item-label', function () {
            let t = $(this);
            if (!t.parent().hasClass('active')) {
                $('.child-menu-item').removeClass('active');
                t.parent().addClass('active');
            }

            // 执行输入框显示
            $('.cjb-radio-group').show();
            $('.cjb-val-group').show();
            // $('#option .cjb-input-block').eq(0).show().siblings().hide()
            // 呼出编辑器 假装动态加载（‘—’）！！！
            _load(function () {
                $('.wx-editor-show').show(), $('.editor-tips').hide();
            }, 200)
            setFormVal(getMenuVal(t), 2);
            ot = t;
        })

        // 设置菜单内容
        function setMenuVal(arr) {
            ot.attr('name', arr['name']);
            if (arr['type'] != '') ot.attr('type', arr['type']);
            if (arr['val'] != '') ot.attr('val', arr['val']);
            if (arr['appid'] != '') ot.attr('appid', arr['appid']);
            if (arr['pagepath'] != '') ot.attr('pagepath', arr['pagepath']);
            if (arr['url'] != '') ot.attr('url', arr['url']);
        }

        // 设置编辑器内容
        function setFormVal(val_arr) {
            $('#content').val(val_arr['val'])
            $("input[name='cjb-name']").val(val_arr['name']);
            if (val_arr['type'] != 'undefined') {
                $(".cjb-radio").removeClass('select');
                $(".cjb-radio[type='" + val_arr['type'] + "']").addClass('select');
                let checkedIndex = $(".cjb-radio[type='" + val_arr['type'] + "']").index()
                if (checkedIndex != -1) {
                    $('#option .cjb-input-block').eq(checkedIndex).show().siblings().hide()
                } else {
                    $('#option .cjb-input-block').eq(0).show().siblings().hide()
                }
            }

        }

        // 获取菜单内容
        function getMenuVal(obj) {
            let arr = new Array();
            arr['name'] = obj.attr('name');
            arr['type'] = obj.attr('type');
            arr['val'] = obj.attr('val');
            return arr;
        }

        // 删除菜单属性和隐藏输入框
        function delMenuVal(obj) {
            // layer.msg('已自动清除菜单类型和值');
            obj.removeAttr('type');
            obj.removeAttr('val');
            // 执行输入框隐藏
            $('.cjb-radio-group').hide();
            $('.cjb-val-group').hide();
        }

        // 单选框选择事件
        $('.cjb-radio').on('click', function () {
            if (!$(this).hasClass('select')) {
                $(this).addClass('select').siblings('.cjb-radio').removeClass('select');
            }
            $('#option').children().eq($(this).index()).show().siblings().hide()
        })

        // 获取表单内容
        function getFormVal() {
            let arr = new Array();
            arr['name'] = $("input[name='cjb-name']").val();
            let indexs = getRadioIndex();
            if (getRadioVal() == 'click') {
                arr['val'] = $("#content").val();
                arr['type'] = getRadioVal();
            } else if (getRadioVal() == 'miniprogram' || getRadioVal() == 'miniprogram_video') {
                arr['appid'] = '{$data["applet_app_id"]}'
                arr['url'] = '#'
                arr['type'] = 'miniprogram'
                if (indexs === 0) {
                    arr['pagepath'] = `/components/yjy-video-slide/yjy-video-slide?${$('#video_id').val()}`
                } else {
                    arr['pagepath'] = $('#menu_url').val()
                }
            }
            return arr;
        }

        // 获取单选框选中的值
        function getRadioVal() {
            let val;
            $('.cjb-radio').each(function () {
                if ($(this).hasClass('select')) {
                    val = $(this).attr('type');
                }
            });
            return val;
        }
        // 获取单选框选中的下标
        function getRadioIndex() {
            let val;
            $('.cjb-radio').each(function () {
                if ($(this).hasClass('select')) {
                    val = $(this).index();
                }
            });
            return val;
        }
        // 字符长度
        function strlen(str) {
            var len = 0;
            for (var i = 0; i < str.length; i++) {
                var c = str.charCodeAt(i);
                if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
                    len++;
                }
                else {
                    len += 2;
                }
            }
            return len;
        }

        // 添加一级菜单
        $(document).on('click', '.add-menu', function () {
            $(this).parent().find('.menu-item').length == 2 ? $(this).hide() : '';
            if ($(this).parent().find('.menu-item').length >= 3) {
                return false;
            }
            let html = '';
            html += '<li class="menu-item">';
            html += '<span class="item-text menu-item-label" name="菜单名称" type="view">菜单名称</span>';
            html += '<ul class="menu-child-list">';
            html += '<span class="triangle"><em></em></span>';
            html += '<li class="add-item"><i class="fa fa-plus"></i></li>';
            html += '</ul>';
            html += '</li>';
            $(this).before(html);
            setMenuWidth();
        })

        /*添加二级菜单*/
        $("body").off().on('click', '.add-item', function () {
            const t = $(this);
            delMenuVal(t.parents('.menu-item').children('span'));
            const list_length = t.parent().find('.child-menu-item').length + 1;
            if (list_length > 4) t.hide();
            let child_html = null;
            child_html = "<li class=\"child-menu-item\"><span class='item-text child-menu-item-label' name=\"子菜单" + list_length + "\" type=\"view\">子菜单" + list_length + "</span></li>";
            t.parent().prepend(child_html);
        })

        // 删除菜单
        $('.menu-delete').on('click', function () {
            ot.parent().remove();
            // 执行表单隐藏
            $('.wx-editor-show').hide();
            $('.editor-tips').show();
            // 显示添加按钮
            if ($('.wx-footer').find('.menu-item').length < 3) {
                $('.add-menu').show();
            }
            setMenuWidth()
        })

        // 菜单名称编辑
        $("input[name='cjb-name']").keyup(function () {
            let val = $(this).val();
            $('.title').text(val)
            ot.text(val);
        })

        // 保存修改
        $('.set_menu').on('click', function () {
            setMenuVal(getFormVal());
            layer.msg('修改成功');
        })
        setMenuWidth();
        // 设置菜单宽度
        function setMenuWidth() {
            let item_length = $('.wx-footer').children().length;
            let _width;
            if (item_length > 3) {
                _width = 100 / (item_length - 1);
            } else {
                _width = 100 / item_length;
            }
            $('.wx-footer').children().each(function () {
                $(this).width(_width + '%');
            })
        }

        /**
         * 编辑器加载方法
         * @param callback 回调方法
         * @param out_time 停止时间
         * @private
         */
        function _load(callback, out_time) {
            $('.editor-load').show();
            $('.wx-editor-show').hide();
            let load = setTimeout(function () {
                $('.editor-load').hide();
                clearTimeout(load);
                if (typeof callback == 'function') {
                    callback();
                }
            }, out_time)
        }

        /**
         * 获取菜单数据对象
         * @returns {{menu: {button: Array}}}
         */
        function getMenuList() {
            let arr = [], i = 0, child_list = [];
            $('.menu-item').each(function () {
                let than = $(this);
                let t = than.children('.menu-item-label');
                let type = t.attr('type');

                const item = {
                    'name': t.attr('name')
                };
                let child_length = than.find('.child-menu-item').length;
                if (child_length == 0) {
                    if (typeof type != 'undefined') {
                        let val = t.attr('val');
                        let appid = t.attr('appid');
                        let pagepath = t.attr('pagepath');
                        let url = t.attr('url');

                        item.type = type;
                        // if (type == 'view') {
                        //     item.url = t.attr('val');
                        // } else {
                        //     item.key = t.attr('val');
                        // }
                        if (type == 'click') {
                            item.key = val.split('_')[1] ? val : '3_' + val;
                        } else if (type == 'miniprogram') {
                            item.appid = appid;
                            item.pagepath = pagepath;
                            item.url = url;
                        }
                    }
                } else {
                    let i = 0;
                    than.find('.child-menu-item').each(function () {
                        let child_than = $(this);
                        let ct = child_than.children('.child-menu-item-label');
                        let name = ct.attr('name');
                        let type = ct.attr('type');
                        let val = ct.attr('val');
                        let appid = ct.attr('appid');
                        let pagepath = ct.attr('pagepath');
                        let url = ct.attr('url');
                        child_list[i] = {
                            'name': name,
                            'type': type
                        }
                        // if (type == 'view') {
                        //     child_list[i].url = val;
                        // }
                        if (type == 'click') {
                            console.log(val,val.split('_')[0])
                            child_list[i].key = val.split('_')[1] ? val : '3_' + val;
                        } else if (type == 'miniprogram') {
                            child_list[i].appid = appid;
                            child_list[i].url = url;
                            child_list[i].pagepath = pagepath;
                        }
                        i++;
                    })
                    item.sub_button = child_list;
                }
                // 清除内存
                child_list = [];
                arr.push(item);
            })
            // 整理并返回数据
            return ({
                'menu': {
                    "button": arr
                }
            })
        }

        /**
         * 初始化菜单方法
         * @param object data 菜单的json数据
         */
        function setMenuList(data) {
            let obj = data;
            // 先删除所有菜单
            $('.menu-item').remove();
            for (let i in obj) {
                let type = '', val = '';
                if (typeof obj[i].type != 'undefined') {
                    type = obj[i].type;
                }
                if (typeof obj[i].url != 'undefined') {
                    val = obj[i].url;
                } else if (typeof obj[i].key != 'undefined') {
                    val = obj[i].key;
                }
                let html = '';
                html += '<li class="menu-item">';
                let appid = '';//appid
                let url = '';//url
                let pagepath = '';//pagepath
                switch (obj[i].type) {
                    // case 'view':
                    //     v = obj[i].url
                    //     break;
                    case 'click':
                        v = obj[i].key.split('_')[1] ? obj[i].key.split('_')[1] : obj[i].key
                        break;
                    case 'miniprogram':
                        appid =  obj[i].appid
                        url =  obj[i].url
                        pagepath =  obj[i].pagepath
                        break;
                }
                html += '<span class="item-text menu-item-label" name="' + obj[i].name + '" type="' + type + '" val="' + val + '" appid="' + appid + '" url="' + url + '" pagepath="' + pagepath + '">' + obj[i].name + '</span>';
                html += '<ul class="menu-child-list">';
                let count_child_menu = 0;
                if (typeof obj[i].sub_button != 'undefined') {
                    for (let j in obj[i].sub_button) {
                        let v = '';//val
                        let appid = '';//appid
                        let url = '';//url
                        let pagepath = '';//pagepath
                        switch (obj[i].sub_button[j].type) {
                            // case 'view':
                            //     v = obj[i].sub_button[j].url
                            //     break;
                            case 'click':
                                v = obj[i].sub_button[j].key.split('_')[1] ? obj[i].sub_button[j].key.split('_')[1] : obj[i].sub_button[j].key
                                break;
                            case 'miniprogram':
                                appid =  obj[i].sub_button[j].appid
                                url =  obj[i].sub_button[j].url
                                pagepath =  obj[i].sub_button[j].pagepath
                                break;
                        }
                        
                        html += '<li class="child-menu-item"><span class="item-text child-menu-item-label" name="' + obj[i].sub_button[j].name + '" type="' + obj[i].sub_button[j].type + '" val="' + v + '" appid="' + appid + '" url="' + url + '" pagepath="' + pagepath + '">' + obj[i].sub_button[j].name + '</span></li>';
                        count_child_menu++;
                    }
                }
                html += '<span class="triangle"><em></em></span>';
                if (count_child_menu >= 5) {
                    html += '<li class="add-item" style="display: none;"><i class="fa fa-plus"></i></li>';
                } else {
                    html += '<li class="add-item"><i class="fa fa-plus"></i></li>';
                }
                html += '</ul>';
                html += '</li>';
                $('.add-menu').before(html);
            }
        }
        // 得到适用于微信自定义菜单接口格式的数据
        $('.create_menu').on('click', function () {

            // setMenuVal(getFormVal());
            let info = getMenuList();
            console.log(JSON.stringify(info.menu))
            console.log(info.menu)
            Ajax('/cps/officialAccount/menuSetting', {
                is_push: $(this).data('is_push'),
                content: JSON.stringify(info.menu),
                id:$('#menuID').val()
            }).then(data => {
                if (data.code === 200) {
                    layer.msg(data.message, {
                        icon: 6
                    });
                } else {
                    layer.alert(data.message);
                }
            })
        })
    </script>
</body>

</html>